package com.gimi.cloud.jimi.gateway.service.impl;


import com.gimi.cloud.jimi.common.enums.common.RedisKeyEnum;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.RedisServiceImpl;
import com.gimi.cloud.jimi.dto.sys.SysConfigDTO;
import com.gimi.cloud.jimi.gateway.service.ExemptionService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by shazhiwei on 2017/10/26.
 */
@Service
public class ExemptionServiceImpl implements ExemptionService {
    private final SysConfigDao sysConfigDao;
    private final RedisServiceImpl redisService;

    public ExemptionServiceImpl(SysConfigDao sysConfigDao,RedisServiceImpl redisService){
        this.sysConfigDao = sysConfigDao;
        this.redisService = redisService;
    }
    @Override
    public Map<String, String> getExemptionMap() {
        Map<String, String> result = new HashMap<>();
        try{
            String redisData = redisService.get(RedisKeyEnum.JIMI_CONFIG_PRE.getKey() + "exemption_service_name");
            if(!StringUtil.isBlank(redisData)){
                //result = JsonUtil.jsonToMap(redisData);
                result.putAll(JsonUtil.jsonToMap(redisData));
            }else {
                Map<String, String> reload = reloadExemption();
                if(reload != null){
                    result = reload;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    private Map<String, String> reloadExemption(){
        Map<String, String> result = null;
        List<SysConfigDTO> sysConfigDTOS = sysConfigDao.getConfigByCfkey("exemption_service_name");
        if(sysConfigDTOS != null && sysConfigDTOS.size()>0){
            SysConfigDTO dto = sysConfigDTOS.get(0);
            String mysqlData = dto.getCfValue();
            Map<String, String> dataMap = JsonUtil.jsonToMap(mysqlData);
            if(dataMap != null && dataMap.size() > 0){
                result = JsonUtil.jsonToMap(mysqlData);
                redisService.set(RedisKeyEnum.JIMI_CONFIG_PRE.getKey() + "exemption_service_name",mysqlData);
            }
        }
        return result;
    }
}
